package com.user.notiy.server.imp;

import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Level;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.user.notiy.common.utils.NoticeList;
import com.user.notiy.dao.TNoticeMapper;
import com.user.notiy.entity.TNotice;
import com.user.notiy.server.NoticeServer;


@Service
public class NoticeStrverImpl implements NoticeServer {
	private static Logger log = LogManager.getLogger(NoticeStrverImpl.class);									//log4j日志
	private static final Level NOTICE = Level.forName("NOTIC", 320);
	
	@Autowired
	private TNoticeMapper tNoticeDAO;
	
	@Override
	public boolean save(TNotice notice) {
		try {
			tNoticeDAO.save(notice);			
			return true;
		} catch (Exception e) {
			log.error("登记通知表失败！");
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public boolean updateNeedNotice() {
		try {
			tNoticeDAO.updateNeedNotice();			
			return true;
		} catch (Exception e) {
			log.error("更新通知表失败！");
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public boolean updateWaitNotice() {
		try {
			tNoticeDAO.updateWaitNotice();			
			return true;
		} catch (Exception e) {
			log.error("更新通知表失败！");
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public List<TNotice> selectWaitNotice() {
		return tNoticeDAO.selectWaitNotice();
	}

	@Override
	@Transactional
	public boolean addList() {
		/* 更新为待通知 */
		tNoticeDAO.updateNeedNotice();
		
		/* 添加到通知队列 */
		List<TNotice> notices = tNoticeDAO.selectWaitNotice();
		int i = 0;
		for(TNotice notice : notices) {
			NoticeList.add(notice.getNoticeType(), notice.getInChlID(), notice.getMap());
			i++;
		}
		log.log(NOTICE, "本次共添加[" + i + "]条待通知消息...\n" + NoticeList.getInfo());

		/* 修改为通知中 */
		tNoticeDAO.updateWaitNotice();
		
		return false;
	}
	
	
	
	public boolean save(TNotice notice,String Orgid){
		try {
			log.info("判断该机构是否需通知");
			List<Map<String, Object>> queryOrgNoticIs = tNoticeDAO.queryOrgNoticIs(Orgid);
			if(queryOrgNoticIs != null && queryOrgNoticIs.size() > 0){
				log.info("["+Orgid+"]["+queryOrgNoticIs+"]该渠道需通知");
				Map<String, Object> map = queryOrgNoticIs.get(0);
				notice.setNoticeType(map.get("NOTICE_TYPE").toString());
				notice.setNoticeMaxNum(map.get("NOTICE_MAX_NUM").toString());
				notice.setNoticeGroup(Orgid);
				boolean save = save(notice);
				return save;
			}else{
				log.info("["+Orgid+"]该渠道无需通知");
				return true;
			}
		} catch (Exception e) {
			log.info("["+Orgid+"]添加通知队列表异常["+e+"]");
			return false;
		}
	}
}
